package com.cysyz.web.modules.base.support.filter;


import com.cysyz.web.modules.base.support.ServletActionContext;
import com.cysyz.web.modules.base.support.ThreadLocalContext;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 如果当前session中没有用户，那么就自动进行登录。用于开发中，省去手动登录的麻烦。
 */
@WebFilter(urlPatterns = "/*")
public class ServletActionContextFilter implements Filter {
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

        ThreadLocalContext context = ServletActionContext.getContext();
        if (context == null) {
            ThreadLocalContext.createNewContext();
        }
        ServletActionContext.setRequest((HttpServletRequest) request);
        ServletActionContext.setResponse((HttpServletResponse) response);

        chain.doFilter(request, response);

        ServletActionContext.remove();
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
